$(function() {
//Declare variable
var  Amount= $( "#Amount" ),
			Discount = $( "#Discount" ),
			Type = $( "#Type" ),
			Product = $( "#Product" ),
			Description = $( "#Description" ),
			EffectiveDateFrom=$("#EffectiveDateFrom"),
			EffectiveDateTo=$("#EffectiveDateTo"),			
			allFields = $( [] ).add( Amount ).add(Discount)
								.add(Description)
								.add(EffectiveDateFrom)
								.add(EffectiveDateTo)	,
			tips = $( ".validateTips" ),
			button_name="",
			url="a_extra_discount.php", 
			ID="",
			rowID=0,
			selectid=1,
			AddTitle="Add Discount Special",	
			EditTitle="Update Discount Special",
			rowSelect="";
			
			
		$("#Amount,#Discount").numeric();
		
		$( "#EffectiveDateFrom" ).datepicker({ dateFormat: 'dd/mm/yy',
						showOn: "button",
						buttonImage: "images/Calendar.png",
						buttonImageOnly: true });
						
		$( "#EffectiveDateTo" ).datepicker({ dateFormat: 'dd/mm/yy',
				showOn: "button",
				buttonImage: "images/Calendar.png",
				buttonImageOnly: true });	
				
		$.get(url, {'c':'p'},function(data){
				var obj=eval('('+data+')');
				 if (obj!=null) {
					$.each(obj, function(index, text) {
						$("#Product").prepend(
							$('<option></option>').val(index).html(text)
						 );
					});
				}	
		});
			
		//Load First page
		LoadData(1,true);
		
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='8' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};	
		
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}
		function AddErrorMessage(o,n){
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		}
		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
					
		function getData(id){

			var dataSet={'id':id,'m':'detail'};  
			//alert(id);
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					var obj=eval('('+data+')');
				 //alert(data);
					Amount.val(obj['Amount']);
					Type.val(obj['iType']);
					if (obj['iType']=="2"){ //cash
						$("#tr_premium").hide();
						$("#tr_cash").show();
						Discount.val(obj['DiscountName']);
					}else{
						$("#tr_premium").show();
						$("#tr_cash").hide();
						Product.val(obj['Discount']);
					}
					$("#EffectiveDateFrom").val(obj["StartDate_"]);
					$("#EffectiveDateTo").val(obj["EndDate_"]);
					Description.val(obj['Description']);
				}
			});
		}
		
		function callAjax(obj,id){
			
			var m=$("#mode").val();
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id},
				success: function(data){
				
					if (data=='error'){
						AddErrorMessage(Amount, "Amount " + Amount.val() + " already exists");
					}else{
						LoadData(selectid,true);
						$( "#dialog-form" ).dialog( "close" );
					}
				}
			});
		}
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			zIndex:9999,
			height: 400,
			width: 450,
			modal: true,
			open: function() { 
				allFields.val( "" );
				tips.text( "* fields are required." );
				if ($("#mode" ).val() =="edit" || $("#mode" ).val()=="view"){
					getData(ID);
				}else if ($("#mode").val()=="add"){
					if (Type.val()==1)//Premium
					{
						$("#tr_premium").show();
						$("#tr_cash").hide();
					}else{
						$("#tr_premium").hide();
						$("#tr_cash").show();
						}
				}else{

					allFields.val( "" );
				}
			},
			close: function() {
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function getValue(){
			var discount;
			if (Type.val()==1){
				discount= Product.val();
			}else{
				discount= Discount.val();
			}
			var o = {'Amount':parseFloat(Amount.val(),10)
						,'Type' : Type.val()
						,'Discount':discount
						,'Description' : Description.val()
						,'StartDate':$("#EffectiveDateFrom").val()
						,'EndDate':$("#EffectiveDateTo").val()					
					};
			return o;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( Amount, " Amount ",1);
			if (Type.val()==2){
				bValid = bValid && checkInputFile( Discount, " Amount ",1);				
			}
			bValid = bValid && checkInputFile( EffectiveDateFrom, "Effective Date From",1);
			bValid = bValid && checkInputFile( EffectiveDateTo, "Effective Date To",1);
			bValid = bValid && checkValidDate( EffectiveDateFrom, EffectiveDateTo, "Effective Date From is less than Effective Date To");			
			return bValid;
		}
		function checkValidDate(ef,et,n){
			var splitarray_f = new Array(); 
			var splitarray_t = new Array(); 
			
			splitarray_f = ef.val().split("/");
			splitarray_t = et.val().split("/");
			
			var date1 = new Date(splitarray_f[2]+"/"+splitarray_f[1]+"/"+splitarray_f[0]);
			var date2 = new Date(splitarray_t[2]+"/"+splitarray_t[1]+"/"+splitarray_t[0]);
			 
			if (date1 > date2)
			{
				ef.addClass( "ui-state-error" );
				et.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			}
			else 
			{
				return true;
			}
		}		
		$("#Type").change(function(){
			if ($(this).val()==1){
				$("#tr_premium").show();
				$("#tr_cash").hide();
			}else{
				$("#tr_premium").hide();
				$("#tr_cash").show();			
			}
		});
		
		//Add Button
		$( "#btnAdd" ).live('click',function() {
			//set mode
			$("#mode").val("add");
			//set title
			$("#dialog-form").dialog({'title':AddTitle});
			$( "#dialog-form" ).dialog( "open" );
			$( "#dialog-form" ).dialog( "option","buttons",{
				"Create":function(){
					allFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
						callAjax(getValue(),0); // call ajax function for add new data
						//$( this ).dialog( "close" );
					}
				},
				"Cancel":function(){$( this ).dialog( "close" );}
			});
			return false;
		});
			
		$(".btnEdit").live('click',function() {
				$("#mode").val("edit"),
				rowSelect=$(this).parent().parent(),
				ID=$(this).parent().parent().find("td").eq(1).html(),
				//getData(ID),
				$("#dialog-form").dialog({'title':EditTitle});
				$("#dialog-form").dialog("open");
				$("#dialog-form").dialog( "option","buttons",{
					"Update":function(){
						var bValid = true;
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl() ) {
							callAjax(getValue(),ID); // call ajax for update 
							$( this ).dialog( "close" );
						}
					}
					,"Cancel":function(){
						$( this ).dialog( "close" );
					}
				}
				);
				return false;
			});
		$(".btnDel").live('click',function(){
				rowSelect = $(this).parent().parent();
				ID=$(this).parent().parent().find("td").eq(1).html();
				$("#mode").val("del");
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						callAjax({"id":ID},0); 	//Call Ajax delete data
						rowSelect.remove(); // remove row
						//Remove number
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						
						
						$( this ).dialog( "close" );
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
			});
		 
		$("#btnSearch").click(function(){
			LoadData(1,true);
 			
		});
		
	function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			var dataSet={'m':'search'
						,'type':$("#cboType").val()
						,'page':page
						};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
			//alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				 
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){
							// var p="<ul>";
					// for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						// p = p +'<li id="'+i+'">'+i+'</li>';
					// }
					// p = p+"</ul>";
					// $("#paging_button ul").remove();
					// $("#paging_button").append(p);
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}					
					 
				}
				//$("#"+page).css({'background-color' : '#006699'});
			 });
		}
 
			
		function setPaging(iTotal){
					 $("#paging_btn").paginate({
					count 		: iTotal,
					start 		: 1,
					display     : 10,
					border					: false,
					text_color  			: '#888',
					background_color    	: '#EEE',	
					text_hover_color  		: 'blue',
					background_hover_color	: '#CFCFCF',
					mouse					: 'press',
					onChange     			: function(page){
												LoadData(page,false);
											  }
				});
			}	
		
});
	